package com.atguigu.gmall.serviceutil.config;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/8/28 23:28
 */
@Slf4j
@RestControllerAdvice
public class AppGlobalException {
    @Value("${spring.application.name}")
    private String appName;
    // 处理自定义异常
    @ExceptionHandler(GmallException.class)
    public Result handleGmallException(GmallException e){
        log.error("{} 业务异常：{}", appName, e);
        // 处理自定义异常
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.error("ServletRequestAttributes is null");
        }

        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();
        Map<String, String[]> parameterMap = request.getParameterMap();
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        Map<String, Object> requestInfo = new HashMap<>();
        requestInfo.put("url", url.toString());
        requestInfo.put("params", parameterMap);
        requestInfo.put("appName", appName);
        fail.setData(requestInfo);
        return fail;
    }
    //处理系统异常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("{} 系统异常：{}", appName,e);
        // 处理系统异常
        Result<Object> fail = Result.fail();
        fail.setCode(500);
        fail.setMessage("系统异常");
        Map<String, Object> requestInfo = new HashMap<>();
        requestInfo.put("appName", appName);
        fail.setData(requestInfo);
        return fail;
    }


}
